package edu.cdnu.controller;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import edu.cdnu.utils.CaptchaUtils;

/**
 * 验证码请求
 * @author ASUS AsingZ
 */
@Controller
public class CaptchaController {
	
	//linux下图形界面显示问题，通过开启headless模式，问题解决。
	static {
        System.setProperty("java.awt.headless", "true");
    }
	
	/**
	 * 验证码
	 * @param time
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("/captcha")
	public void validateCode(String time, HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		// 创建图片缓存
		BufferedImage bi = new BufferedImage(CaptchaUtils.WIDTH, CaptchaUtils.HEIGHT, BufferedImage.TYPE_INT_RGB);

		// 获得画布
		Graphics g = bi.getGraphics();
		// 设置背景颜色
		CaptchaUtils.setBackGroundColor(g);
		// 设置边框
		CaptchaUtils.setBorder(g);
		// 绘制干扰线
		CaptchaUtils.drawRandomLine(g);

		// 产生随机汉字验证码
		String randomChar = CaptchaUtils.drawRandomChar((Graphics2D) g);// 强制转换

		// 将产生的随机汉字验证码存进session中进行保存
//		String id = request.getSession().getId();
//        jedisClient.set("captcha_" + id, randomChar);
//        jedisClient.expire("captcha_" + id, 120);

		HttpSession session = request.getSession();
		session.setAttribute("captcha", randomChar);
		
		//设置验证码的有效时间  以秒为单位
		session.setMaxInactiveInterval(60*5);

		// 设置响应信息的类型为图片类型
		response.setContentType("image/jpeg");

		// 控制Http缓存，设置响应头信息，防止浏览器缓存
		response.setDateHeader("expries", -1);
		response.setHeader("Cache-Control", "no-Cache");
		response.setHeader("Pargma", "no-Cache");

		// 将验证码图片写到浏览器中
		ImageIO.write(bi, "jpg", response.getOutputStream());
	}
}
